package world.xuewei.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import world.xuewei.model.entity.CommodityReview;
import world.xuewei.model.entity.R;
import world.xuewei.service.CommodityReviewService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/commodity_review")
public class CommodityReviewController {

    @Resource
    private CommodityReviewService commodityReviewService;

    /**
     * 添加评论
     */
    @PostMapping("/add")
    public R addReview(@RequestBody CommodityReview review,HttpServletRequest request) {
        String userIdStr = (String) request.getAttribute("userId");
        review.setUserId(Long.parseLong(userIdStr));
        if (commodityReviewService.addReview(review)) {
            return R.ok().message("评论成功");
        }
        return R.error().message("评论失败");
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/delete/{id}")
    public R deleteReview(@PathVariable Long id, @RequestParam Long userId) {
        if (commodityReviewService.deleteReview(id, userId)) {
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    /**
     * 获取商品评论列表
     */
    @GetMapping("/list/{commodityId}")
    public R getReviewList(@PathVariable Long commodityId) {
        List<CommodityReview> reviews = commodityReviewService.getReviewsByCommodityId(commodityId);
        return R.ok().data("reviews", reviews);
    }
}